/**
 * clue控制器
 *
 * @author sxf
 * @email sxf02615@163.com
 * @date 2025/1/15
 */
package com.sxf.crm.controller;


import com.sxf.crm.dto.*;
import com.sxf.crm.enums.CluePriority;
import com.sxf.crm.enums.ClueSource;
import com.sxf.crm.enums.ClueStatus;
import com.sxf.crm.service.ClueService;
import com.sxf.crm.service.ClueFollowUpService;
import com.sxf.crm.util.SecurityUtils;

import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/clues")
@RequiredArgsConstructor
public class ClueController {
    
    private static final Logger logger = LoggerFactory.getLogger(ClueController.class);
    private final ClueService clueService;
    private final ClueFollowUpService clueFollowUpService;

    @GetMapping
    @PreAuthorize("hasAuthority('clue:list')")
    public ResponseEntity<Page<ClueDTO>> listClues(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) ClueSource source,
            @RequestParam(required = false) ClueStatus status,
            @RequestParam(required = false) CluePriority priority,
            Pageable pageable) {

        logger.debug("查询线索列表: name={}, source={}, status={}, priority={}", name, source, status, priority);
        return ResponseEntity.ok(clueService.listClues(name, source, status, priority, pageable));
    }
    
    @PostMapping
    @PreAuthorize("hasAuthority('clue:create')")
    public ResponseEntity<ClueDTO> createClue(@Valid @RequestBody ClueRequest request) {
        logger.debug("创建线索: {}", request);

        Long currentUserId = SecurityUtils.getCurrentUserId();
        String currentUsername = SecurityUtils.getCurrentUsername();
        
        logger.debug("创建线索: 当前用户ID={}, 用户名={}", currentUserId, currentUsername);
        
        return ResponseEntity.ok(clueService.createClue(request,currentUserId));
    }
    
    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('clue:edit')")
    public ResponseEntity<ClueDTO> updateClue(@PathVariable Long id, @Valid @RequestBody ClueRequest request) {
        logger.debug("更新线索: id={}, request={}", id, request);
        Long currentUserId = SecurityUtils.getCurrentUserId();
        String currentUsername = SecurityUtils.getCurrentUsername();
        logger.debug("更新线索: 当前用户ID={}, 用户名={}", currentUserId, currentUsername);
        return ResponseEntity.ok(clueService.updateClue(id, request,currentUserId));
    }
    
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('clue:delete')")
    public ResponseEntity<Void> deleteClue(@PathVariable Long id) {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        String currentUsername = SecurityUtils.getCurrentUsername();
        clueService.deleteClue(id,currentUserId);
        logger.debug("删除线索: 当前用户ID={}, 用户名={}", currentUserId, currentUsername);
        return ResponseEntity.ok().build();
    }
    
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('clue:view')")
    public ResponseEntity<ClueDTO> getClue(@PathVariable Long id) {
        logger.debug("获取线索详情: id={}", id);
        return ResponseEntity.ok(clueService.getClue(id));
    }
    
    @PostMapping("/{id}/assign")
    @PreAuthorize("hasAuthority('clue:assign')")
    public ResponseEntity<Void> assignClue(@PathVariable Long id, @RequestBody @Valid ClueAssignRequest request) {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        String currentUsername = SecurityUtils.getCurrentUsername();
        logger.debug("分配线索: 当前用户ID={}, 用户名={}, id={}, ownerId={}", currentUserId, currentUsername, id, request.getOwnerId());
        clueService.assignClue(id, request.getOwnerId(),currentUserId);
        return ResponseEntity.ok().build();
    }
    
    @PostMapping("/{id}/claim")
    @PreAuthorize("hasAuthority('clue:claim')")
    public ResponseEntity<Void> claimClue(@PathVariable Long id) {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        String currentUsername = SecurityUtils.getCurrentUsername();
        logger.debug("领取线索: 当前用户ID={}, 用户名={}, id={}", currentUserId, currentUsername, id);
        clueService.claimClue(id,currentUserId);
        return ResponseEntity.ok().build();
    }
        
    @PostMapping("/{id}/accept")
    @PreAuthorize("hasAuthority('clue:accept')")
    public ResponseEntity<Void> acceptClue(@PathVariable Long id) {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        String currentUsername = SecurityUtils.getCurrentUsername();
        logger.debug("接受线索: 当前用户ID={}, 用户名={}, id={}", currentUserId, currentUsername, id);
        clueService.acceptClue(id,currentUserId);
        return ResponseEntity.ok().build();
    }
    
    @PostMapping("/{id}/recycle")
    @PreAuthorize("hasAuthority('clue:recycle')")
    public ResponseEntity<Void> recycleClue(@PathVariable Long id, @RequestBody ClueRecycleRequest request) {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        String currentUsername = SecurityUtils.getCurrentUsername();
        logger.debug("回收线索: 当前用户ID={}, 用户名={}, id={}", currentUserId, currentUsername, id);
        clueService.recycleClue(id,currentUserId,request);
        return ResponseEntity.ok().build();
    }
        
    @PostMapping("/{id}/convert")
    @PreAuthorize("hasAuthority('clue:convert')")
    public ResponseEntity<Void> convertClue(@PathVariable Long id, @RequestBody ClueConvertRequest request) {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        String currentUsername = SecurityUtils.getCurrentUsername();
        logger.debug("转化线索: 当前用户ID={}, 用户名={}, id={}, convertType={}, convertReason={}", currentUserId, currentUsername, id, request.getConvertType(), request.getConvertReason());
        clueService.convertClue(id, request,currentUserId);
        return ResponseEntity.ok().build();
    }
    
    @GetMapping("/{id}/followups")
    @PreAuthorize("hasAuthority('clue:followup')")
    public ResponseEntity<List<ClueFollowUpDTO>> listFollowUps(@PathVariable Long id) {
        logger.debug("获取线索跟进记录: clueId={}", id);
        return ResponseEntity.ok(clueFollowUpService.listByClueId(id));
    }
    
    @PostMapping("/{id}/followups")
    @PreAuthorize("hasAuthority('clue:followup')")
    public ResponseEntity<ClueFollowUpDTO> addFollowUp(@PathVariable Long id, @RequestBody ClueFollowUpRequest request) {
        logger.debug("添加线索跟进: clueId={}, request={}", id, request);
        Long currentUserId = SecurityUtils.getCurrentUserId();
        String currentUsername = SecurityUtils.getCurrentUsername();
        logger.debug("添加线索跟进: 当前用户ID={}, 用户名={}, clueId={}, request={}", currentUserId, currentUsername, id, request);
        return ResponseEntity.ok(clueFollowUpService.addFollowUp(id, request,currentUserId));
    }
    
    @DeleteMapping("/followups/{followUpId}")
    @PreAuthorize("hasAuthority('clue:followup')")
    public ResponseEntity<Void> deleteFollowUp(@PathVariable Long followUpId) {
        logger.debug("删除跟进记录: followUpId={}", followUpId);
        Long currentUserId = SecurityUtils.getCurrentUserId();
        String currentUsername = SecurityUtils.getCurrentUsername();
        logger.debug("删除跟进记录: 当前用户ID={}, 用户名={}, followUpId={}", currentUserId, currentUsername, followUpId);
        clueFollowUpService.deleteFollowUp(followUpId,currentUserId);
        return ResponseEntity.ok().build();
    }
    
    @GetMapping("/unassigned")
    @PreAuthorize("hasAuthority('clue:list')")
    public ResponseEntity<List<ClueDTO>> getUnassignedClues() {
        logger.debug("获取未分配的线索");
        return ResponseEntity.ok(clueService.getUnassignedClues());
    }
    
    @GetMapping("/my")
    @PreAuthorize("hasAuthority('clue:list')")
    public ResponseEntity<List<ClueDTO>> getMyClues() {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        String currentUsername = SecurityUtils.getCurrentUsername();
        logger.debug("获取我的线索: 当前用户ID={}, 用户名={}", currentUserId, currentUsername);
        return ResponseEntity.ok(clueService.getUserClues(currentUserId));
    }
} 